<?php

namespace app\admin\controller\course;

use app\common\controller\Backend;
use app\common\model\Classes;
use app\common\model\School;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教师任教
 *
 * @package app\admin\controller
 */
class Teach extends Backend
{


    /**
     * @var \app\common\model\Teach
     */
    protected $model = null;
    protected $noNeedRight = ['searchList', 'cxSelect'];
    protected $schoolLimit = true;
    protected $modelValidate = true;
    //protected $modelSceneValidate = true;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Teach');

        $this->view->assign('typeData', \app\common\model\Teach::$type_list);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('teach')
                ->join('__SCHOOL__ school', 'school.id = teach.school_id', 'left')
                ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id', 'left')
                ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id', 'left')
                ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('teach')
                ->join('__SCHOOL__ school', 'school.id = teach.school_id', 'left')
                ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id', 'left')
                ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id', 'left')
                ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                ->where($where)
                ->field('teach.*,school.name school_name,subject.name subject_name,user.nickname teacher_name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['type_text'])->toArray();

                foreach ($list as $key => $value) {
                    $list[$key]['classes_count'] = count(explode(',', $value['class_ids'])) . ' 个班';
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ($this->schoolLimit && $this->schoolLimitFieldAutoFill) {
                    $params[$this->schoolLimitField] = $this->auth->school_id;
                }

                //检测同一教师、同一学科、同一班级不能重复任教
                $class_ids = explode(',', $params['class_ids']);
                $classes = Classes::whereIn('id', $class_ids)->column('id,name');
                if (!$classes) {
                    $this->error('您选择的班级不存在');
                }
                $params['class_ids'] = implode(',', array_keys($classes));
                $teaches = \app\common\model\Teach::where([
                    'school_id' => $params['school_id'],
                    'teacher_id' => $params['teacher_id'],
                    'subject_id' => $params['subject_id']
                ])->field('id,class_ids')->select();
                if ($teaches) {
                    $have_class_ids = array_column($teaches, 'class_ids');
                    $have_class_ids = explode(',', implode(',', $have_class_ids));

                    $repeat_ids = array_intersect($class_ids, $have_class_ids);

                    if ($repeat_ids) {
                        $error_classes = [];
                        foreach ($repeat_ids as $key => $id) {
                            if (isset($classes[$id])) {
                                $error_classes[] = $classes[$id];
                            }
                        }

                        $this->error("班级「".implode(',', $error_classes)."」重复任教");
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);


                    $teacher = \app\common\model\Teacher::get($params['teacher_id']);
                    if (!$teacher) {
                        $this->error('教师不存在');
                    }

                    $subject = \app\common\model\Subject::get($params['subject_id']);
                    if (!$subject) {
                        $this->error('学科不存在');
                    }

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/teach/add', [
                        'form_params' => [
                            'user_id' => $teacher->user_id,
                            'class_ids' => $params['class_ids'],
                            'school_id' => $teacher->school_id,
                            'subject_id' => $params['subject_id'],
                            'subject_name' => $subject->name,
                        ]
                    ]);
                    $response->getStatusCode();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('admin', ['class_ids' => []]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->with('teacher')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $teacher = \app\common\model\Teacher::where('id', $params['teacher_id'])->find();
                if (!$teacher) {
                    $this->error('教师不存在');
                }

                $subject = \app\common\model\Subject::get($params['subject_id']);
                if (!$subject) {
                    $this->error('学科不存在');
                }

                //检测同一教师、同一学科、同一班级不能重复任教
                $class_ids = explode(',', $params['class_ids']);
                $classes = Classes::whereIn('id', $class_ids)->column('id,name');
                if (!$classes) {
                    $this->error('您选择的班级不存在');
                }
                $params['class_ids'] = implode(',', array_keys($classes));
                $teaches = \app\common\model\Teach::where([
                    'school_id' => $params['school_id'],
                    'teacher_id' => $params['teacher_id'],
                    'subject_id' => $params['subject_id'],
                    'id' => ['<>', $ids]
                ])->field('id,class_ids')->select();
                if ($teaches) {
                    $have_class_ids = array_column($teaches, 'class_ids');
                    $have_class_ids = explode(',', implode(',', $have_class_ids));

                    $repeat_ids = array_intersect($class_ids, $have_class_ids);

                    if ($repeat_ids) {
                        $error_classes = [];
                        foreach ($repeat_ids as $key => $id) {
                            if (isset($classes[$id])) {
                                $error_classes[] = $classes[$id];
                            }
                        }

                        $this->error("班级「".implode(',', $error_classes)."」重复任教");
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $form_params = [
                        'old' => [
                            'user_id' => $row['teacher']['user_id'],
                            'subject_id' => $row['subject_id'],
                            'class_ids' => $row['class_ids'],
                        ],
                        'new' => [
                            'user_id' => $teacher['user_id'],
                            'subject_id' => $params['subject_id'],
                            'subject_name' => $subject['name'],
                            'class_ids' => $params['class_ids'],
                            'school_id' => $teacher['school_id'],
                        ]
                    ];

                    $result = $row->allowField(true)->save($params);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/teach/edit', [
                        'form_params' => $form_params
                    ]);
                    $content = $response->getStatusCode();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $teachers = \app\common\model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.school_id', $row['school_id'])
            ->column('teacher.id,user.nickname');
        $subjects = \app\common\model\Subject::where('school_id', $row['school_id'])->column('id,name');

        $this->view->assign('teacherList', build_select('row[teacher_id]', $teachers, $row['teacher_id'], ['class' => 'form-control selectpicker teacher']));
        $this->view->assign('subjectList', build_select('row[subject_id]', $subjects, $row['subject_id'], ['class' => 'form-control selectpicker subject']));

        $this->assignconfig('admin', ['class_ids' => explode(',', $row['class_ids'])]);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->with('teacher')->where($pk, 'in', $ids)->select();

            Db::startTrans();
            try {
                $delete_ids = array_column($list, $pk);

                $this->model->whereIn('id', $delete_ids)->delete();

                $post_data = [];
                foreach ($list as $key => $value) {
                    $post_data[] = [
                        'user_id' => $value['teacher']['user_id'],
                        'subject_id' => $value['subject_id'],
                        'class_ids' => $value['class_ids'],
                    ];
                }

                $client = new Client([
                    'base_uri' => config('suzhi.url'),
                    'timeout' => 30,
                    'allow_redirects' => true
                ]);
                $response = $client->request('POST', '/platform/teach/del', [
                    'form_params' => [
                        'data' => $post_data,
                    ]
                ]);
                $status = $response->getStatusCode();

                Db::commit();

                $this->success();

            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
